#!/usr/bin/env ruby
require 'rubygems'
require 'socket'
require 'optparse'
require 'pp'
require 'inifile'
require 'eventmachine'
require 'rexml/document'
require 'logger'
include REXML

options = {}

optparse = OptionParser.new do |opts|
	opts.banner = "Usage: #{$0} [options] port"
	options[:config] = 'server.ini'
	options[:logfile] = 'log.txt'
	opts.on('-l', '--logfile FILE', 'log file location') do |file|
		options[:logfile] = file
	end
	opts.on('-c', '--config FILE', 'INI config file') do |file|
		options[:config] = file
	end
	opts.on('-h', '--help', 'Display this screen') do
		puts opts
		exit
	end

end

begin
	optparse.parse!
rescue OptionParser::InvalidOption => e
	puts e
	puts optparse
	exit
end

begin
	ini = IniFile.new options[:config], :parameter => '='
	print ini['src']['ip'], ':', ini['src']['port'], "\n"
	print ini['dst']['ip'], ':', ini['dst']['port'], "\n"
	#ini.write
rescue 
	print 'error: ', $!, '\n'
end

log = Logger.new 'log.txt', 'daily'

exit if defined?(Ocra)

=begin
module PortListener
	def receive_data(data)
		send_data(data)
	end
end

EventMachine::run do
	EventMachine::start_server ini['src']['ip'], ini['src']['port'], PortListener
	puts "Started PortListener on #{ini['src']['ip']}:#{ini['src']['port']}"
end
=end

server = TCPServer.new(ini['src']['ip'], ini['src']['port'])
while (session = server.accept)
	puts "log: Connection from #{session.peeraddr[2]} at #{session.peeraddr[3]}"
	input = session.gets()
	log.debug input

	xmldoc = Document.new input
	pc_text = XPath.first xmldoc, "/CountingNotificationEntry/Count/text()"
	unless pc_text
		puts 'received unrecognized message'
		log.debug 'unrecognized XML'
		next
	end

	puts "diff people count : #{pc_text.value}"

	difference = pc_text.value.to_s
	puts "==>#{difference}"

	dest = TCPSocket.open(ini['dst']['ip'], ini['dst']['port']) rescue false
	if dest
		header_ba = [0x05, 0x00, 0x00, 0x00, 0x00, 0x90, 0x01] << difference.to_s.length
		#data_ba = difference.to_s.unpack('U*')
		data_ba = difference.to_s.bytes.to_a
		checksum_ba = Array(data_ba.each.inject { |a,b| a^b })
		end_ba = [0x04]
		packet = header_ba.pack('c*') + data_ba.pack('U*') + checksum_ba.pack('c*') + end_ba.pack('c*')
		puts "#{header_ba.pack('c*').length}, #{data_ba.pack('U*').length}, #{checksum_ba.pack('c*').length}, #{end_ba.pack('c*').length}"
		bytes_sent = dest.write packet
		puts "#{bytes_sent} sent"
		dest.close
	end
			
	puts "log: sending goodbye"
	session.close
end
